﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Entities;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace mozhi.smarterp.Business.Repositories
{
    public class DocumentEfCoreRepository<TDbContext, TEntity, TKey> : EfCoreRepository<TDbContext, TEntity, TKey>, IDocumentRepository<TEntity, TKey> where TDbContext : IEfCoreDbContext where TEntity : DocumentAggregateRoot, IEntity<TKey>
    {
        public DocumentEfCoreRepository(IDbContextProvider<TDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public virtual async Task<int> GetCountAsync(string number, Guid? excludeId, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var count = await dbContext.Set<TEntity>().AsNoTracking()
                .WhereIf(!number.IsNullOrEmpty(), x => x.Number == number)
                .WhereIf(excludeId.HasValue, x => x.Id != excludeId)
                .CountAsync();

            return count;
        }

        public virtual async Task<string> GetLastNumberAsnyc(CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var lastNumber = await dbContext.Set<TEntity>().AsNoTracking().MaxAsync(x => x.Number);

            return lastNumber;
        }
    }
}
